import { useMutation, useQueryClient } from '@tanstack/react-query';
import { Form, Input, message, Modal, Select } from 'antd';
import React from 'react';

import api from '@/apis/api';
import localINFO from '@/utils/localInfo';
import { UsbRegisterRole } from '@/utils/usbKey/register';

import { Logger } from '../useLogger';

interface AddUserModalProps {
  visible: boolean;
  setVisible: (visible: boolean) => void;
}

const AddUserModal: React.FC<AddUserModalProps> = ({ visible, setVisible }) => {
  const { Option } = Select;
  const [form] = Form.useForm();

  const queryClient = useQueryClient();

  const AddUser = useMutation({
    mutationFn: (params: any) => api.AddUser(params),
    onSuccess: (res: any) => {
      if (res?.success) {
        message.open({
          type: 'success',
          key: 'userAdd',
          content: '添加成功',
        });
        form.resetFields();
        setVisible(false);
      } else {
        message.open({
          type: 'error',
          key: 'userAdd',
          content: `添加失败，${res?.message}`,
        });
      }
    },
    onError: (error: any) => {
      Logger(error);
      message.error('添加失败');
    },
    onSettled: () => queryClient.invalidateQueries({ queryKey: ['getUsersData'] }),
    mutationKey: ['getUsersData'],
  });

  const handleaddOk = async () => {
    await form.validateFields();
    const publickey = await UsbRegisterRole();
    const data: FieldType = form.getFieldsValue();
    AddUser.mutate({
      username: data.username,
      password: data.password,
      grant: data.userRole,
      public_key: publickey,
    });
  };

  const handleaddCancel = () => {
    form.resetFields();
    setVisible(false);
  };

  type FieldType = {
    username?: string;
    password?: string;
    userRole?: number;
    rpassword?: string;
  };

  return (
    <>
      <Modal
        title="添加用户"
        open={visible}
        onOk={handleaddOk}
        onCancel={handleaddCancel}
        cancelText="取消"
        okText="确定"
        okButtonProps={{ disabled: localINFO.getRoleId() !== 1 }}
      >
        <p style={{ marginLeft: 24, color: 'red' }}>
          注意：该操作会清空当前usbKey内的角色信息！
        </p>
        <Form
          form={form}
          preserve={false}
          name="basic"
          labelCol={{ span: 6 }}
          wrapperCol={{ span: 16 }}
          style={{ maxWidth: 600, height: 220 }}
          autoComplete="off"
        >
          <Form.Item<FieldType>
            label="用户名"
            name="username"
            rules={[{ required: true, message: '请输入用户名！' }]}
          >
            <Input autoComplete="new-user" maxLength={30} placeholder="请输入用户名" />
          </Form.Item>

          <Form.Item<FieldType>
            label="密码"
            name="password"
            rules={[{ required: true, message: '请输入密码！' }]}
          >
            <Input.Password autoComplete="new-password" placeholder="请输入密码" />
          </Form.Item>

          <Form.Item<FieldType>
            label="确认密码"
            name="rpassword"
            rules={[
              ({ getFieldValue }) => ({
                validator(rule, value) {
                  if (!value || getFieldValue('password') === value) {
                    return Promise.resolve(rule);
                  }
                  return Promise.reject('两次密码不同！');
                },
              }),
              { required: true, message: '请再输入密码!' },
            ]}
          >
            <Input.Password autoComplete="new-password" placeholder="请输入密码" />
          </Form.Item>

          <Form.Item<FieldType>
            label="用户角色"
            name="userRole"
            rules={[{ required: true, message: '请选择用户角色！' }]}
          >
            <Select placeholder="请选择用户角色">
              <Option value={0}>管理员</Option>
              <Option value={1}>操作员</Option>
            </Select>
          </Form.Item>
        </Form>
      </Modal>
    </>
  );
};

export default AddUserModal;
